﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;

namespace Chart.Net
{
    public class Report
    {
        private Collection<Chart> entities = new Collection<Chart>();
        
        public string Title { get; set; }
        public Collection<Chart> Entities
        {
            get { return entities; }
        }

        public string GetHtml()
        {
            StringBuilder result = new StringBuilder();
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            Dictionary<Type, bool> headFlags = new Dictionary<Type, bool>();
            foreach(Chart entity in entities)
            {
                if (!headFlags.ContainsKey(entity.GetType()))
                {
                    head.Append(entity.GetScripts());
                    headFlags.Add(entity.GetType(), true);
                }
                body.Append(entity.GetBody());
            }
            string defaultTemplate = Utility.ReadTemplate(Constants.TemplateScaffold);
            result.AppendFormat(defaultTemplate, Title, head, body);
            return result.ToString() ;
        }

        public string Save()
        {
            string filePath = string.Format(@"Reports\{0}-{1}.html",
                string.IsNullOrEmpty(Title) ? "untitled" : Title.Replace(' ', '_'), 
                DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"));
            File.WriteAllText(filePath, GetHtml(), Encoding.UTF8);
            return filePath;
        }
    }
}
